Ext.namespace("Microtraining.Admin.Practice");
Mt = Microtraining.Admin;
Mt.Practice={
	/**
	 * 全局配置
	 */
	Config:{
		/**
		 *分页:每页显示记录数
		 */
		PageSize:15,
		/**
		 *显示配置
		 */
		View:{
			/**
			 * 显示练习题的视图相对练习题列表Grid的位置`
			 * 1:上方,2:下方,3:左侧,4:右侧,
			 */
			Direction:2,
			/**
			 *是否显示。
			 */
			IsShow:0,
			/**
			 * 是否固定显示练习题信息页(或者打开新窗口)
			 */
			IsFix:0
		},
        /**
         * 在线编辑器类型。
         * 1:CkEditor,2:KindEditor,3:xhEditor
         * 配合Action的变量配置$online_editor
         */
        OnlineEditor:1
	},
	/**
	 * Cookie设置
	 */
	Cookie:new Ext.state.CookieProvider(),
	/**
	 * 初始化
	 */
	Init:function(){
		if (Mt.Practice.Cookie.get('View.Direction')){
			Mt.Practice.Config.View.Direction=Mt.Practice.Cookie.get('View.Direction');
		}
		if (Mt.Practice.Cookie.get('View.IsFix')!=null){
			Mt.Practice.Config.View.IsFix=Mt.Practice.Cookie.get('View.IsFix');
		}
        if (Ext.util.Cookies.get('OnlineEditor')!=null){
            Mt.Practice.Config.OnlineEditor=parseInt(Ext.util.Cookies.get('OnlineEditor'));
        }

	}
};
/**
 * Model:数据模型
 */
Mt.Practice.Store = {
	/**
	 * 练习题
	 */
	practiceStore:new Ext.data.Store({
		reader: new Ext.data.JsonReader({
			totalProperty: 'totalCount',
			successProperty: 'success',
			root: 'data',remoteSort: true,
			fields : [
                {name: 'practice_id',type: 'int'},
                {name: 'lesson_id',type: 'int'},
                {name: 'lesson_name',type: 'string'},
                {name: 'chapter_id',type: 'int'},
                {name: 'chapter_name',type: 'string'},
                {name: 'practice_title',type: 'string'},
                {name: 'practice_titleShow',type:'string'},
                {name: 'options_json',type: 'string'},
                {name: 'answer',type: 'int'},
                {name: 'point',type: 'int'},
                {name: 'isShow',type: 'string'},
                {name: 'sort_order',type: 'int'}
			]}
		),
		writer: new Ext.data.JsonWriter({
			encode: false
		}),
		listeners : {
			beforeload : function(store, options) {
				if (Ext.isReady) {
					if (!options.params.limit)options.params.limit=Mt.Practice.Config.PageSize;
					Ext.apply(options.params, Mt.Practice.View.Running.practiceGrid.filter);//保证分页也将查询条件带上
				}
			}
		}
	}),

  optionStore:new Ext.data.ArrayStore({
    fields : [
      {name : 'oid',type : 'string'},
      {name : 'title',type : 'string'},
      {name : 'current',type : 'int'},
    ]
  }),
    /**
     * 企业课程
     */
    lessonStoreForCombo:new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'home/admin/src/httpdata/lesson.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'lessons',
            autoLoad: true,
            totalProperty: 'totalCount',
            idProperty: 'lesson_id'
        }, [
            {name: 'lesson_id', mapping: 'lesson_id'},
            {name: 'lesson_name', mapping: 'lesson_name'}
        ])
    }),
    chapterStoreForCombo:new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'home/admin/src/httpdata/chapter.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'chapters',
            autoLoad: true,
            totalProperty: 'totalCount',
            idProperty: 'chapter_id'
        }, [
            {name: 'chapter_id', mapping: 'chapter_id'},
            {name: 'chapter_name', mapping: 'chapter_name'}
        ])
    })
};
/**
 * View:练习题显示组件
 */
Mt.Practice.View={
	/**
	 * 编辑窗口：新建或者修改练习题
	 */
	EditWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 自定义类型:保存类型
				 * 0:保存窗口,1:修改窗口
				 */
				savetype:0,
				closeAction : "hide",
				constrainHeader:true,maximizable: true,collapsible: true,
				width : 450,height : 550,minWidth : 400,minHeight : 450,
				layout : 'fit',plain : true,buttonAlign : 'center',
				defaults : {
					autoScroll : true
				},
				listeners:{
					beforehide:function(){
						this.editForm.form.getEl().dom.reset();
					},
                    afterrender:function(){}
				},
				items : [
					new Ext.form.FormPanel({
						ref:'editForm',layout:'form',
						labelWidth : 100,labelAlign : "center",
						bodyStyle : 'padding:5px 5px 0',align : "center",
						api : {},
						defaults : {
							xtype : 'textfield',anchor:'98%'
						},
						items : [
              {xtype: 'hidden',name : 'practice_id',ref:'../practice_id'},
              {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
              {xtype: 'hidden',name : 'chapter_id',ref:'../chapter_id'},
              {xtype: 'hidden',name : 'options_json',ref:'../options_json'},
              {
                   fieldLabel : '课程',xtype: 'combo',name : 'lesson_name',ref : '../lesson_name',
                   store:Mt.Practice.Store.lessonStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',allowBlank:false,
                   loadingText: '查询中...',width: 570, pageSize:Mt.Practice.Config.PageSize,
                   displayField:'lesson_name',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                           '<h3>{lesson_name}</h3>',
                       '</div></tpl>'
                   ),
                   listeners:{
                       'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                       if(this.fireEvent('beforeselect', this, record, index) !== false){
                          this.grid.lesson_id.setValue(record.data.lesson_id);
                          this.grid.lesson_name.setValue(record.data.lesson_name);
                          this.collapse();

                          this.grid.chapter_id.setValue('');
                          this.grid.chapter_name.setValue('');

                          var comStore = Ext.getCmp("comChapter");
                          comStore.store.load({ params: { lesson_id: record.id.toString() } });
                       }
                   }
              },
              {
                   fieldLabel : '章节',xtype: 'combo',name : 'chapter_name',ref : '../chapter_name', id:'comChapter',
                   store:Mt.Practice.Store.chapterStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',allowBlank:false,
                   loadingText: '查询中...',width: 570, pageSize:Mt.Practice.Config.PageSize,
                   displayField:'chapter_name',grid:this,
                   mode: 'local',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                           '<h3>{chapter_name}</h3>',
                       '</div></tpl>'
                   ),
                   listeners:{
                       'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                       if(this.fireEvent('beforeselect', this, record, index) !== false){
                          this.grid.chapter_id.setValue(record.data.chapter_id);
                          this.grid.chapter_name.setValue(record.data.chapter_name);
                          this.collapse();
                       }
                   }
              },
              {fieldLabel : '题目',name : 'practice_title',xtype : 'textarea',id:'practice_title',ref:'practice_title',allowBlank:false},
              // {fieldLabel : '答案',name : 'answer',xtype : 'numberfield'},
              {fieldLabel : '分值',name : 'point',xtype : 'numberfield',allowBlank:false},
              {fieldLabel : '排序',name : 'sort_order',xtype : 'numberfield',value:1} ,
              {fieldLabel : '是否显示',hiddenName : 'isShow'
                   ,xtype:'combo',ref:'../isShow',mode : 'local',triggerAction : 'all',
                   lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
                   store : new Ext.data.SimpleStore({
                       fields : ['value', 'text'],
                       data : [['0', '否'], ['1', '是']]
                   }),emptyText: '请选择是否显示',
                   valueField : 'value',displayField : 'text'
              },
              Mt.Practice.View.Running.optionGrid
              
              
						]
					})
				],
				buttons : [{
					text: "",ref : "../saveBtn",scope:this,
					handler : function() {

						if (!this.editForm.getForm().isValid()) {
							return;
						}
            var option_store = Mt.Practice.View.Running.optionGrid.store;
            if (option_store.getCount() < 2) {
              Ext.Msg.alert("提示", "请添加至少2个选项");
              return;
            };

            var optsions_json=new Array();
            var has_current_option=false;

            option_store.each(function(record) {
                optsions_json.push(record.data);
                if (!has_current_option) {
                  has_current_option = record.data.current;
                };
            });

            if (!has_current_option) {
              Ext.Msg.alert("提示", "请添加至少1个正确选项");
              return;
            };
            this.editForm.getForm().findField('options_json').setValue(Ext.encode(optsions_json));

						editWindow=this;
						if (this.savetype==0){
							this.editForm.api.submit=ExtServicePractice.save;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Ext.Msg.alert("提示", "保存成功！");
									Mt.Practice.View.Running.practiceGrid.doSelectPractice();
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}else{
							this.editForm.api.submit=ExtServicePractice.update;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Mt.Practice.View.Running.practiceGrid.store.reload();
									Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
										Mt.Practice.View.Running.practiceGrid.bottomToolbar.doRefresh();
									}});
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}
					}
				}, {
					text : "取 消",scope:this,
					handler : function() {
						this.hide();
					}
				}, {
					text : "重 置",ref:'../resetBtn',scope:this,
					handler : function() {
						this.editForm.form.loadRecord(Mt.Practice.View.Running.practiceGrid.getSelectionModel().getSelected());

					}
				}]
			}, config);
			Mt.Practice.View.EditWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 显示练习题详情
	 */
	PracticeView:{
		/**
		 * Tab页：容器包含显示与练习题所有相关的信息
		 */
		Tabs:Ext.extend(Ext.TabPanel,{
			constructor : function(config) {
				config = Ext.apply({
					region : 'south',collapseMode : 'mini',split : true,
					activeTab: 1, tabPosition:"bottom",resizeTabs : true,
					header:false,enableTabScroll : true,tabWidth:'auto', margins : '0 3 3 0',
					defaults : {
						autoScroll : true,
						layout:'fit'
					},
					listeners:{
						beforetabchange:function(tabs,newtab,currentTab){
							if (tabs.tabFix==newtab){
								if (Mt.Practice.View.Running.practiceGrid.getSelectionModel().getSelected()==null){
									Ext.Msg.alert('提示', '请先选择练习题！');
									return false;
								}
								Mt.Practice.Config.View.IsShow=1;
								Mt.Practice.View.Running.practiceGrid.showPractice();
								Mt.Practice.View.Running.practiceGrid.tvpView.menu.mBind.setChecked(false);
								return false;
							}
						}
					},
					items: [
						{title:'+',tabTip:'取消固定',ref:'tabFix',iconCls:'icon-fix'}
					]
				}, config);
				Mt.Practice.View.PracticeView.Tabs.superclass.constructor.call(this, config);

				this.onAddItems();
			},
			/**
			 * 根据布局调整Tabs的宽度或者高度以及折叠
			 */
			enableCollapse:function(){
				if ((Mt.Practice.Config.View.Direction==1)||(Mt.Practice.Config.View.Direction==2)){
					this.width =Ext.getBody().getViewSize().width;
					this.height=Ext.getBody().getViewSize().height/2;
				}else{
					this.width =Ext.getBody().getViewSize().width/2;
					this.height=Ext.getBody().getViewSize().height;
				}
				this.ownerCt.setSize(this.width,this.height);
				if (this.ownerCt.collapsed)this.ownerCt.expand();
				this.ownerCt.collapsed=false;
			},
			onAddItems:function(){
				this.add(
					{title: '基本信息',ref:'tabPracticeDetail',iconCls:'tabs',
					 tpl: [
						 '<table class="viewdoblock">',
                         '    <tr class="entry"><td class="head">课程</td><td class="content">{lesson_name}</td></tr>',
                         '    <tr class="entry"><td class="head">题目</td><td class="content">{practice_titleShow}</td></tr>',
                         // '    <tr class="entry"><td class="head">答案</td><td class="content">{answer}</td></tr>',
                         '    <tr class="entry"><td class="head">分值</td><td class="content">{point}</td></tr>',
                         '    <tr class="entry"><td class="head">排序</td><td class="content">{sort_order}</td></tr>',
						 '</table>'
					 ]}
				);
                this.add(
                    {title: '其他',iconCls:'tabs'}
                );
			}
		}),
		/**
		 * 窗口:显示练习题信息
		 */
		Window:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					title:"查看练习题",constrainHeader:true,maximizable: true,minimizable : true,
					width : 705,height : 500,minWidth : 450,minHeight : 400,
					layout : 'fit',resizable:true,plain : true,bodyStyle : 'padding:5px;',
					closeAction : "hide",
					items:[new Mt.Practice.View.PracticeView.Tabs({ref:'winTabs',tabPosition:'top'})],
					listeners: {
						minimize:function(w){
							w.hide();
							Mt.Practice.Config.View.IsShow=0;
							Mt.Practice.View.Running.practiceGrid.tvpView.menu.mBind.setChecked(true);
						},
						hide:function(w){
							Mt.Practice.View.Running.practiceGrid.tvpView.toggle(false);
						}
					},
					buttons: [{
						text: '新增练习题',scope:this,
						handler : function() {this.hide();Mt.Practice.View.Running.practiceGrid.addPractice();}
					},{
						text: '修改练习题',scope:this,
						handler : function() {this.hide();Mt.Practice.View.Running.practiceGrid.updatePractice();}
					}]
				}, config);
				Mt.Practice.View.PracticeView.Window.superclass.constructor.call(this, config);
			}
		})
	},

	/**
	 * 窗口：批量上传练习题
	 */
	UploadWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				title : '批量上传练习题数据',width : 400,height : 110,minWidth : 300,minHeight : 100,
				layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
				items : [
					new Ext.form.FormPanel({
						ref:'uploadForm',fileUpload: true,
						width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
						frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
						defaults: {
							anchor: '95%',allowBlank: false,msgTarget: 'side'
						},
						items : [{
							xtype : 'fileuploadfield',
							fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
							emptyText: '请上传练习题Excel文件',buttonText: '',
							accept:'application/vnd.ms-excel',
							buttonCfg: {iconCls: 'upload-icon'}
						}]
					})
				],
				buttons : [{
						text : '上 传',
						scope:this,
						handler : function() {
							uploadWindow           =this;
							validationExpression   =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
							var isValidExcelFormat = new RegExp(validationExpression);
							var result             = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
							if (!result){
								Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
								return;
							}
							if (this.uploadForm.getForm().isValid()) {
								Ext.Msg.show({
									title : '请等待',msg : '文件正在上传中，请稍后...',
									animEl : 'loading',icon : Ext.Msg.WARNING,
									closable : true,progress : true,progressText : '',width : 300
								});
								this.uploadForm.getForm().submit({
									url : 'index.php?go=admin.upload.uploadPractice',
									success : function(form, response) {
										Ext.Msg.alert('成功', '上传成功');
										uploadWindow.hide();
										uploadWindow.uploadForm.upload_file.setValue('');
										Mt.Practice.View.Running.practiceGrid.doSelectPractice();
									},
									failure : function(form, response) {
										Ext.Msg.alert('错误', response.result.data);
									}
								});
							}
						}
					},{
						text : '取 消',
						scope:this,
						handler : function() {
							this.uploadForm.upload_file.setValue('');
							this.hide();
						}
					}]
				}, config);
			Mt.Practice.View.UploadWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 视图：练习题列表
	 */
	Grid:Ext.extend(Ext.grid.GridPanel, {
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 查询条件
				 */
				filter:null,
				region : 'center',
				store : Mt.Practice.Store.practiceStore,
				sm : this.sm,
				frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
				loadMask : true,stripeRows : true,headerAsText : false,
				defaults : {
					autoScroll : true
				},
				cm : new Ext.grid.ColumnModel({
					defaults:{
						width:100,sortable : true
					},
					columns : [
						this.sm,
                        {header : '标识',dataIndex : 'practice_id',hidden:true},
                        {header : '课程',dataIndex : 'lesson_name'},
                        {header : '章节',dataIndex : 'chapter_name'},
                        {header : '题目',dataIndex : 'practice_titleShow',width:300},
                        // {header : '答案',dataIndex : 'answer'},
                        {header : '分值',dataIndex : 'point'},
                        {header : '排序',dataIndex : 'sort_order'}
                        ,{header : '是否显示',dataIndex : 'isShow',renderer:function(value){if (value == true) {return "是";}else{return "否";}}}
					]
				}),
				tbar : {
					xtype : 'container',layout : 'anchor',height : 27 * 2,style:'font-size:14px',
					defaults : {
						height : 27,anchor : '100%'
					},
					items : [
						new Ext.Toolbar({
							enableOverflow: true,width : 100,
							defaults : {
								xtype : 'textfield',
								listeners : {
								   specialkey : function(field, e) {
										if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectPractice();
									}
								}
							},
							items : [
                '课程','&nbsp;&nbsp;',{ref: '../plesson_id',xtype: 'combo',
                     store:Mt.Practice.Store.lessonStoreForCombo,hiddenName : 'lesson_id',
                     emptyText: '请选择课程',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:280,pageSize:Mt.Practice.Config.PageSize,
                     displayField:'lesson_name',valueField:'lesson_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                         '<tpl for="."><div class="search-item">',
                         '<h3>{lesson_name}</h3>',
                         '</div></tpl>'
                     )
                },'&nbsp;&nbsp;',
                '题目','&nbsp;&nbsp;',{ref: '../ppractice_title'},'&nbsp;&nbsp;',
								{
									xtype : 'button',text : '查询',scope: this,
									handler : function() {
										this.doSelectPractice();
									}
								},
								{
									xtype : 'button',text : '重置',scope: this,
									handler : function() {
                                        this.topToolbar.plesson_id.setValue("");
                                        this.topToolbar.ppractice_title.setValue("");
										this.filter={};
										this.doSelectPractice();
									}
								}]
						}),
						new Ext.Toolbar({
							defaults:{scope: this},
							items : [
								{
									text: '反选',iconCls : 'icon-reverse',
									handler: function(){
										this.onReverseSelect();
									}
								},'-',{
									text : '添加练习题',iconCls : 'icon-add',
									handler : function() {
										this.addPractice();
									}
								},'-',{
									text : '修改练习题',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
									handler : function() {
										this.updatePractice();
									}
								},'-',{
									text : '删除练习题', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
									handler : function() {
										this.deletePractice();
									}
								},'-',{
									xtype:'tbsplit',text: '导入', iconCls : 'icon-import',
									handler : function() {
										this.importPractice();
									},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'批量导入练习题',iconCls : 'icon-import',scope:this,handler:function(){this.importPractice()}}
										]}
								},'-',{
									text : '导出',iconCls : 'icon-export',
									handler : function() {
										this.exportPractice();
									}
								},'-',{
									xtype:'tbsplit',text: '查看练习题', ref:'../../tvpView',iconCls : 'icon-updown',
									enableToggle: true, disabled : true,
									handler:function(){this.showPractice()},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'上方',group:'mlayout',checked:false,iconCls:'view-top',scope:this,handler:function(){this.onUpDown(1)}},
											{text:'下方',group:'mlayout',checked:true ,iconCls:'view-bottom',scope:this,handler:function(){this.onUpDown(2)}},
											{text:'左侧',group:'mlayout',checked:false,iconCls:'view-left',scope:this,handler:function(){this.onUpDown(3)}},
											{text:'右侧',group:'mlayout',checked:false,iconCls:'view-right',scope:this,handler:function(){this.onUpDown(4)}},
											{text:'隐藏',group:'mlayout',checked:false,iconCls:'view-hide',scope:this,handler:function(){this.hidePractice();Mt.Practice.Config.View.IsShow=0;}},'-',
											{text: '固定',ref:'mBind',checked: true,scope:this,checkHandler:function(item, checked){this.onBindGrid(item, checked);Mt.Practice.Cookie.set('View.IsFix',Mt.Practice.Config.View.IsFix);}}
										]}
								},'-']}
					)]
				},
				bbar: new Ext.PagingToolbar({
					pageSize: Mt.Practice.Config.PageSize,
					store: Mt.Practice.Store.practiceStore,
					scope:this,autoShow:true,displayInfo: true,
					displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
					emptyMsg: "无显示数据",
					listeners:{
						change:function(thisbar,pagedata){
							if (Mt.Practice.Viewport){
								if (Mt.Practice.Config.View.IsShow==1){
									Mt.Practice.View.IsSelectView=1;
								}
								this.ownerCt.hidePractice();
								Mt.Practice.Config.View.IsShow=0;
							}
						}
					},
					items: [
						{xtype:'label', text: '每页显示'},
						{xtype:'numberfield', value:Mt.Practice.Config.PageSize,minValue:1,width:35,
							style:'text-align:center',allowBlank: false,
							listeners:
							{
								change:function(Field, newValue, oldValue){
									var num = parseInt(newValue);
									if (isNaN(num) || !num || num<1)
									{
										num = Mt.Practice.Config.PageSize;
										Field.setValue(num);
									}
									this.ownerCt.pageSize= num;
									Mt.Practice.Config.PageSize = num;
									this.ownerCt.ownerCt.doSelectPractice();
								},
								specialKey :function(field,e){
									if (e.getKey() == Ext.EventObject.ENTER){
										var num = parseInt(field.getValue());
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Practice.Config.PageSize;
										}
										this.ownerCt.pageSize= num;
										Mt.Practice.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectPractice();
									}
								}
							}
						},
						{xtype:'label', text: '个'}
					]
				})
			}, config);
			//初始化显示练习题列表
			this.doSelectPractice();
			Mt.Practice.View.Grid.superclass.constructor.call(this, config);
			//创建在Grid里显示的练习题信息Tab页
			Mt.Practice.View.Running.viewTabs=new Mt.Practice.View.PracticeView.Tabs();
			this.addListener('rowdblclick', this.onRowDoubleClick);
		},
		/**
		 * 行选择器
		 */
		sm : new Ext.grid.CheckboxSelectionModel({
			//handleMouseDown : Ext.emptyFn,
			listeners : {
				selectionchange:function(sm) {
					// 判断删除和更新按钮是否可以激活
					this.grid.btnRemove.setDisabled(sm.getCount() < 1);
					this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					this.grid.tvpView.setDisabled(sm.getCount() != 1);
				},
				rowselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						this.grid.hidePractice();
						Mt.Practice.Config.View.IsShow=0;
					}else{
						if (Mt.Practice.View.IsSelectView==1){
							Mt.Practice.View.IsSelectView=0;
							this.grid.showPractice();
						}
					}
				},
				rowdeselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						if (Mt.Practice.Config.View.IsShow==1){
							Mt.Practice.View.IsSelectView=1;
						}
						this.grid.hidePractice();
						Mt.Practice.Config.View.IsShow=0;
					}
				}
			}
		}),
		/**
		 * 双击选行
		 */
		onRowDoubleClick:function(grid, rowIndex, e){
			if (!Mt.Practice.Config.View.IsShow){
				this.sm.selectRow(rowIndex);
				this.showPractice();
				this.tvpView.toggle(true);
			}else{
				this.hidePractice();
				Mt.Practice.Config.View.IsShow=0;
				this.sm.deselectRow(rowIndex);
				this.tvpView.toggle(false);
			}
		},
		/**
		 * 是否绑定在本窗口上
		 */
		onBindGrid:function(item, checked){
			if (checked){
			   Mt.Practice.Config.View.IsFix=1;
			}else{
			   Mt.Practice.Config.View.IsFix=0;
			}
			if (this.getSelectionModel().getSelected()==null){
				Mt.Practice.Config.View.IsShow=0;
				return ;
			}
			if (Mt.Practice.Config.View.IsShow==1){
			   this.hidePractice();
			   Mt.Practice.Config.View.IsShow=0;
			}
			this.showPractice();
		},
		/**
		 * 反选
		 */
		onReverseSelect:function() {
			for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
				if (this.sm.isSelected(i)) {
					this.sm.deselectRow(i);
				}else {
					this.sm.selectRow(i, true);
				}
			}
		},
		/**
		 * 查询符合条件的练习题
		 */
		doSelectPractice : function() {
			if (this.topToolbar){
                var plesson_id = this.topToolbar.plesson_id.getValue();
                var ppractice_title = this.topToolbar.ppractice_title.getValue();
                this.filter       ={'lesson_id':plesson_id,'practice_title':ppractice_title};
			}
			var condition = {'start':0,'limit':Mt.Practice.Config.PageSize};
			Ext.apply(condition,this.filter);
			ExtServicePractice.queryPagePractice(condition,function(provider, response) {
				if (response.result&&response.result.data) {
					var result           = new Array();
					result['data']       =response.result.data;
					result['totalCount'] =response.result.totalCount;
					Mt.Practice.Store.practiceStore.loadData(result);
				} else {
					Mt.Practice.Store.practiceStore.removeAll();
					Ext.Msg.alert('提示', '无符合条件的练习题！');
				}
			});
		},
		/**
		 * 显示练习题视图
		 * 显示练习题的视图相对练习题列表Grid的位置
		 * 1:上方,2:下方,0:隐藏。
		 */
		onUpDown:function(viewDirection){
			Mt.Practice.Config.View.Direction=viewDirection;
			switch(viewDirection){
				case 1:
					this.ownerCt.north.add(Mt.Practice.View.Running.viewTabs);
					break;
				case 2:
					this.ownerCt.south.add(Mt.Practice.View.Running.viewTabs);
					break;
				case 3:
					this.ownerCt.west.add(Mt.Practice.View.Running.viewTabs);
					break;
				case 4:
					this.ownerCt.east.add(Mt.Practice.View.Running.viewTabs);
					break;
			}
			Mt.Practice.Cookie.set('View.Direction',Mt.Practice.Config.View.Direction);
			if (this.getSelectionModel().getSelected()!=null){
				if ((Mt.Practice.Config.View.IsFix==0)&&(Mt.Practice.Config.View.IsShow==1)){
					this.showPractice();
				}
				Mt.Practice.Config.View.IsFix=1;
				Mt.Practice.View.Running.practiceGrid.tvpView.menu.mBind.setChecked(true,true);
				Mt.Practice.Config.View.IsShow=0;
				this.showPractice();
			}
		},
		/**
		 * 显示练习题
		 */
		showPractice : function(){
			if (this.getSelectionModel().getSelected()==null){
				Ext.Msg.alert('提示', '请先选择练习题！');
				Mt.Practice.Config.View.IsShow=0;
				this.tvpView.toggle(false);
				return ;
			}
			if (Mt.Practice.Config.View.IsFix==0){
				if (Mt.Practice.View.Running.view_window==null){
					Mt.Practice.View.Running.view_window=new Mt.Practice.View.PracticeView.Window();
				}
				if (Mt.Practice.View.Running.view_window.hidden){
					Mt.Practice.View.Running.view_window.show();
					Mt.Practice.View.Running.view_window.winTabs.hideTabStripItem(Mt.Practice.View.Running.view_window.winTabs.tabFix);
					this.updateViewPractice();
					this.tvpView.toggle(true);
					Mt.Practice.Config.View.IsShow=1;
				}else{
					this.hidePractice();
					Mt.Practice.Config.View.IsShow=0;
				}
				return;
			}
			switch(Mt.Practice.Config.View.Direction){
				case 1:
					if (!this.ownerCt.north.items.contains(Mt.Practice.View.Running.viewTabs)){
						this.ownerCt.north.add(Mt.Practice.View.Running.viewTabs);
					}
					break;
				case 2:
					if (!this.ownerCt.south.items.contains(Mt.Practice.View.Running.viewTabs)){
						this.ownerCt.south.add(Mt.Practice.View.Running.viewTabs);
					}
					break;
				case 3:
					if (!this.ownerCt.west.items.contains(Mt.Practice.View.Running.viewTabs)){
						this.ownerCt.west.add(Mt.Practice.View.Running.viewTabs);
					}
					break;
				case 4:
					if (!this.ownerCt.east.items.contains(Mt.Practice.View.Running.viewTabs)){
						this.ownerCt.east.add(Mt.Practice.View.Running.viewTabs);
					}
					break;
			}
			this.hidePractice();
			if (Mt.Practice.Config.View.IsShow==0){
				Mt.Practice.View.Running.viewTabs.enableCollapse();
				switch(Mt.Practice.Config.View.Direction){
					case 1:
						this.ownerCt.north.show();
						break;
					case 2:
						this.ownerCt.south.show();
						break;
					case 3:
						this.ownerCt.west.show();
						break;
					case 4:
						this.ownerCt.east.show();
						break;
				}
				this.updateViewPractice();
				this.tvpView.toggle(true);
				Mt.Practice.Config.View.IsShow=1;
			}else{
				Mt.Practice.Config.View.IsShow=0;
			}
			this.ownerCt.doLayout();
		},
		/**
		 * 隐藏练习题
		 */
		hidePractice : function(){
			this.ownerCt.north.hide();
			this.ownerCt.south.hide();
			this.ownerCt.west.hide();
			this.ownerCt.east.hide();
			if (Mt.Practice.View.Running.view_window!=null){
				Mt.Practice.View.Running.view_window.hide();
			}
			this.tvpView.toggle(false);
			this.ownerCt.doLayout();
		},
		/**
		 * 更新当前练习题显示信息
		 */
		updateViewPractice : function() {

			if (Mt.Practice.View.Running.view_window!=null){
				Mt.Practice.View.Running.view_window.winTabs.tabPracticeDetail.update(this.getSelectionModel().getSelected().data);
			}
			Mt.Practice.View.Running.viewTabs.tabPracticeDetail.update(this.getSelectionModel().getSelected().data);
		},
		/**
		 * 新建练习题
		 */
		addPractice : function() {
      if (Mt.Practice.View.Running.optionGrid==null){
        Mt.Practice.View.Running.optionGrid = new Mt.Practice.View.OptionView.Grid();
      }
      Mt.Practice.View.Running.optionGrid.store.loadData([]);

			if (Mt.Practice.View.Running.edit_window==null){
				Mt.Practice.View.Running.edit_window=new Mt.Practice.View.EditWindow();
			}
			Mt.Practice.View.Running.edit_window.resetBtn.setVisible(false);
			Mt.Practice.View.Running.edit_window.saveBtn.setText('保 存');
			Mt.Practice.View.Running.edit_window.setTitle('添加练习题');
			Mt.Practice.View.Running.edit_window.savetype=0;
			Mt.Practice.View.Running.edit_window.practice_id.setValue("");

			Mt.Practice.View.Running.edit_window.show();
			Mt.Practice.View.Running.edit_window.maximize();
		},

    loadOptions:function(practice_id){
      var filter ={'practice_id':practice_id};
      ExtServicePractice.queryPageOptions(filter,function(provider, response) {
          if (response.result){
              if (response.result.data) {
                var result           = new Array();
                result['data']       =response.result.data;
                result['totalCount'] =response.result.totalCount;
                Mt.Practice.Store.optionStore.loadData(result);
              } else {
                Mt.Practice.Store.optionStore.removeAll();
                Ext.Msg.alert('提示', '无符合条件的选项！');
              }
          }
      });
    },

		/**
		 * 编辑练习题时先获得选中的练习题信息
		 */
		updatePractice : function() {
      if (Mt.Practice.View.Running.optionGrid==null){
        Mt.Practice.View.Running.optionGrid = new Mt.Practice.View.OptionView.Grid();
      }

			if (Mt.Practice.View.Running.edit_window==null){
				Mt.Practice.View.Running.edit_window=new Mt.Practice.View.EditWindow();
			}
			Mt.Practice.View.Running.edit_window.saveBtn.setText('修 改');
			Mt.Practice.View.Running.edit_window.resetBtn.setVisible(true);
			Mt.Practice.View.Running.edit_window.setTitle('修改练习题');
			Mt.Practice.View.Running.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
			Mt.Practice.View.Running.edit_window.savetype=1;

      var data = Ext.decode(this.getSelectionModel().getSelected().data.options_json);
      Mt.Practice.Store.optionStore.loadData(data);

			Mt.Practice.View.Running.edit_window.show();
			Mt.Practice.View.Running.edit_window.maximize();
		},
		/**
		 * 删除练习题
		 */
		deletePractice : function() {
			Ext.Msg.confirm('提示', '确实要删除所选的练习题吗?', this.confirmDeletePractice,this);
		},
		/**
		 * 确认删除练习题
		 */
		confirmDeletePractice : function(btn) {
			if (btn == 'yes') {
				var del_practice_ids ="";
				var selectedRows    = this.getSelectionModel().getSelections();
				for ( var flag = 0; flag < selectedRows.length; flag++) {
					del_practice_ids=del_practice_ids+selectedRows[flag].data.practice_id+",";
				}
				ExtServicePractice.deleteByIds(del_practice_ids);
				this.doSelectPractice();
				Ext.Msg.alert("提示", "删除成功！");
			}
		},
		/**
		 * 导出练习题
		 */
		exportPractice : function() {
			ExtServicePractice.exportPractice(this.filter,function(provider, response) {
				if (response.result.data) {
					window.open(response.result.data);
				}
			});
		},
		/**
		 * 导入练习题
		 */
		importPractice : function() {
			if (Mt.Practice.View.current_uploadWindow==null){
				Mt.Practice.View.current_uploadWindow=new Mt.Practice.View.UploadWindow();
			}
			Mt.Practice.View.current_uploadWindow.show();
		}
	}), 
  OptionView:{
    /**
     *  当前创建的选项编辑窗口
     */
    edit_window:null,
    /**
     * 编辑窗口：新建或者修改选项
     */
    EditWindow:Ext.extend(Ext.Window,{
      constructor : function(config) {
        config = Ext.apply({
          /**
           * 自定义类型:保存类型
           * 0:保存窗口,1:修改窗口
           */
          savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,modal: true,
          width : 450,height : 200,minWidth : 400,minHeight : 200,
          layout : 'fit',plain : true,buttonAlign : 'center',
          defaults : {autoScroll : true},
          listeners:{
            beforehide:function(){
              this.editForm.form.getEl().dom.reset();
            }
          },
          items : [
            new Ext.form.FormPanel({
              ref:'editForm',layout:'form',
              labelWidth : 100,labelAlign : "center",
              bodyStyle : 'padding:5px 5px 0',align : "center",
              api : {},
              defaults : {
                xtype : 'textfield',anchor:'98%'
              },
              items : [
                {xtype: 'hidden',name : 'oid',ref:'../oid'},
                {fieldLabel : '选项',name : 'title',ref:'../otitle',xtype : 'textarea',allowBlank : false }, 
                // {xtype: 'hidden',name : 'current',ref:'../ocurrent'},
                // {fieldLabel : '正确答案',hiddenName : 'current',xtype : 'combo',ref:'../current',mode : 'local',triggerAction : 'all',lazyRender : true,editable: false,allowBlank : false,
                //   store : new Ext.data.SimpleStore({
                //     fields : ['value', 'text'],
                //     data : [['0', '否'], ['1', '是']]
                //   }),emptyText: '请选择...',
                //   valueField : 'value',// 值
                //   displayField : 'text',// 显示文本
                // }
              ]
            })
          ],
          buttons : [{
            text: "",ref : "../saveBtn",scope:this,
            handler : function() {

              if (!this.editForm.getForm().isValid()) {
                return;
              }
              editWindow=this;

              var option_store = Mt.Practice.Store.optionStore;
              var OptionRecord = Ext.data.Record.create([
                     {name: 'oid', type: 'string'},
                     {name: 'title', type: 'string'},
                     {name: 'current', type: 'int'},
                 ]);

              if (this.savetype==0){//保存

                var id = 1;
                 while(option_store.findExact('oid',id) != -1){
                  id++;
                 }

                 var record = new OptionRecord({
                     oid: id,
                     title: editWindow.otitle.getValue(),
                     current: 0
                 }); 
                 option_store.add(record);

              }else{//修改
               var oid = Mt.Practice.View.Running.optionGrid.getSelectionModel().getSelected().id;
               var record = option_store.getById(oid);

               record.set('title',editWindow.otitle.getValue());
               record.set('current',editWindow.current.getValue());
               record.commit();
              }
              editWindow.editForm.getForm().reset()
              editWindow.hide(); 
            }
          }, {
            text : "取 消",scope:this,
            handler : function() {
              this.hide();
            }
          }, {
            text : "重 置",ref:'../resetBtn',scope:this,
            handler : function() {
              this.editForm.form.loadRecord(Mt.Practice.View.Running.optionGrid.getSelectionModel().getSelected());

            }
          }]
        }, config);
        Mt.Practice.View.OptionView.EditWindow.superclass.constructor.call(this, config);
      }
    }),
    /**
     * 查询条件
     */
    filter:null,
    /**
     * 视图：选项列表
     */
    Grid:Ext.extend(Ext.grid.GridPanel, {
      constructor : function(config) {
        config = Ext.apply({
          store : Mt.Practice.Store.optionStore,height:210,
          sm : this.sm,
          frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
          loadMask : true,stripeRows : true,headerAsText : false,
          defaults : {autoScroll : true},
          cm : new Ext.grid.ColumnModel({
            defaults:{
              width:120,sortable : true
            },
            columns : [
              this.sm,
              {header : '标识',dataIndex : 'oid',hidden:true},
              {header : '选项',dataIndex : 'title',width:500},
              {header : '正确答案',dataIndex : 'current',renderer:function(value){
                  return value == 1 ? "是" : "否"
                }
              },
            ]
          }),
          tbar : {
            xtype : 'container',layout : 'anchor',
            height : 27,style:'font-size:14px',
            defaults : {
              height : 27,anchor : '100%'
            },
            items : [
              new Ext.Toolbar({
                defaults:{
                  scope: this
                },
                items : [
                  {
                    text: '反选',iconCls : 'icon-reverse',
                    handler: function(){
                      this.onReverseSelect();
                    }
                  },'-',{
                    text : '添加选项',iconCls : 'icon-add',
                    handler : function() {
                      this.addOption();
                    }
                  },'-',{
                    text : '修改选项',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                      this.updateOption();
                    }
                  },'-',{
                    text : '删除选项', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
                    handler : function() {
                      this.deleteOption();
                    }
                  },'-',
                  {
                    text : '切换正确答案', ref: '../../btnAnswer',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                       this.changeAnswer();
                    }
                  },'-']}
            )]
          } 
        }, config);
        /**
         * 选项数据模型获取数据Direct调用
         */
        Mt.Practice.View.OptionView.Grid.superclass.constructor.call(this, config);
      },
      /**
       * 行选择器
       */
      sm : new Ext.grid.CheckboxSelectionModel({
        listeners : {
          selectionchange:function(sm) {
            // 判断删除和更新按钮是否可以激活
            this.grid.btnRemove.setDisabled(sm.getCount() < 1);
            this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
            this.grid.btnAnswer.setDisabled(sm.getCount() != 1);
          }
        }
      }),
      /**
       * 查询符合条件的选项
       */
      doSelectOption : function() {
        
      },
      /**
       * 反选
       */
      onReverseSelect:function() {
        for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
          if (this.sm.isSelected(i)) {
            this.sm.deselectRow(i);
          }else {
            this.sm.selectRow(i, true);
          }
        }
      },
      /**
       * 新建选项
       */
      addOption : function(){
        if (Mt.Practice.View.OptionView.edit_window==null){
          Mt.Practice.View.OptionView.edit_window=new Mt.Practice.View.OptionView.EditWindow();
        }
        Mt.Practice.View.OptionView.edit_window.resetBtn.setVisible(false);
        Mt.Practice.View.OptionView.edit_window.saveBtn.setText('保 存');
        Mt.Practice.View.OptionView.edit_window.setTitle('添加选项');
        Mt.Practice.View.OptionView.edit_window.savetype=0;
        Mt.Practice.View.OptionView.edit_window.oid.setValue("");
        Mt.Practice.View.OptionView.edit_window.show(); 
      },
      /**
       * 编辑选项时先获得选中的选项信息
       */
      updateOption : function() {
        if (Mt.Practice.View.OptionView.edit_window==null){
          Mt.Practice.View.OptionView.edit_window=new Mt.Practice.View.OptionView.EditWindow();
        }
        Mt.Practice.View.OptionView.edit_window.saveBtn.setText('修 改');
        Mt.Practice.View.OptionView.edit_window.resetBtn.setVisible(true);
        Mt.Practice.View.OptionView.edit_window.setTitle('修改选项');
        Mt.Practice.View.OptionView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
        Mt.Practice.View.OptionView.edit_window.savetype=1;

        Mt.Practice.View.OptionView.edit_window.show(); 
      },
      /**
       * 删除选项
       */
      deleteOption : function() {
        Ext.Msg.confirm('提示', '确实要删除所选的选项吗?', this.confirmDeleteOption,this);
      },

      changeAnswer : function() {
        var option_store = Mt.Practice.Store.optionStore;
        var option = this.getSelectionModel().getSelected().data;

        var oid = Mt.Practice.View.Running.optionGrid.getSelectionModel().getSelected().id;
        var record = option_store.getById(oid);
        
        if (option.current == 1) {
          record.set('current',0);
        }else{
          record.set('current',1);
        }
        record.commit();
      },

      /**
       * 确认删除选项
       */
      confirmDeleteOption : function(btn) {
        if (btn == 'yes') {

          var oid = Mt.Practice.View.Running.optionGrid.getSelectionModel().getSelected().data.oid;
          var option_store = Mt.Practice.Store.optionStore;

          var del_oid ="";
          var selectedRows    = this.getSelectionModel().getSelections();
          for ( var flag = 0; flag < selectedRows.length; flag++) {
            del_oid = selectedRows[flag].data.oid;
            option_store.removeAt(option_store.find('oid',del_oid));
          }
          this.doSelectOption();
          Ext.Msg.alert("提示", "删除成功！");
        }
      }
    })
  },
	/**
	 * 核心内容区
	 */
	Panel:Ext.extend(Ext.form.FormPanel,{
		constructor : function(config) {
			Mt.Practice.View.Running.practiceGrid=new Mt.Practice.View.Grid();
			if (Mt.Practice.Config.View.IsFix==0){
				Mt.Practice.View.Running.practiceGrid.tvpView.menu.mBind.setChecked(false,true);
			}
			config = Ext.apply({
				region : 'center',layout : 'fit', frame:true,
				items: {
					layout:'border',
					items:[
						Mt.Practice.View.Running.practiceGrid,
						{region:'north',ref:'north',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'south',ref:'south',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true,items:[Mt.Practice.View.Running.viewTabs]},
						{region:'west',ref:'west',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'east',ref:'east',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true}
					]
				}
			}, config);
			Mt.Practice.View.Panel.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 当前运行的可视化对象
	 */
	Running:{
		/**
		 * 当前练习题Grid对象
		 */
		practiceGrid:null,
    optionGrid:null,

		/**
		 * 显示练习题信息及关联信息列表的Tab页
		 */
		viewTabs:null,
		/**
		 * 当前创建的编辑窗口
		 */
		edit_window:null,
    option_edit_window:null,
		/**
		 * 当前的显示窗口
		 */
		view_window:null
	}
};
/**
 * Controller:主程序
 */
Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.state.Manager.setProvider(Mt.Practice.Cookie);
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Mt.Practice.Init();
	/**
	 * 练习题数据模型获取数据Direct调用
	 */
	Mt.Practice.Store.practiceStore.proxy=new Ext.data.DirectProxy({
		api: {read:ExtServicePractice.queryPagePractice}
	});
	/**
	 * 练习题页面布局
	 */
	Mt.Practice.Viewport = new Ext.Viewport({
		layout : 'border',
		items : [new Mt.Practice.View.Panel()]
	});
	Mt.Practice.Viewport.doLayout();
	setTimeout(function(){
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({
			remove:true
		});
	}, 250);
});